<template>
    <div class="form">
        <el-form ref="form" :model="obj.data" label-width="80px">
            <div class="label require">基本信息</div>
            <div class="flex-row">
                <el-form-item label="产品名称" prop="title" :rules="[formRulesMixin.notNull]" class="flex1 mr10">
                    <el-input v-model="obj.data.title" placeholder="请输入产品名称" maxlength="50" clearable autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="品牌名称" prop="brand" class="flex1">
                    <el-input v-model="obj.data.brand" placeholder="请输入品牌名称" maxlength="30" clearable autocomplete="off"></el-input>
                </el-form-item>
                <!-- <el-form-item label="货号" prop="itemnumber" :rules="[formRulesMixin.notNull]" class="flex1">
                    <el-input v-model="obj.data.itemnumber" placeholder="请输入货号" maxlength="30" clearable autocomplete="off"></el-input>
                </el-form-item> -->
            </div>
            <div class="flex-row">
                <el-form-item label="计量单位" prop="unit" :rules="[formRulesMixin.notNull]" class="flex1 mr10">
                    <el-select v-model="obj.data.unit" placeholder="请选择计量单位">
                        <el-option v-for="(item,index) in obj.config.计量单位||[]" :key="index" :label="item.name" :value="item.name" />
                    </el-select>
                </el-form-item>
                <el-form-item label="最低单价" prop="min_price" :rules="[formRulesMixin.notNull]" class="flex1">
                    <el-input v-model="obj.data.min_price" type="number" placeholder="请输入最低单价" maxlength="10" clearable autocomplete="off"><template #append>元</template></el-input>
                </el-form-item>
            </div>
            <div class="flex-row">
                <el-form-item label="运输方式" prop="shipping_type" :rules="[formRulesMixin.notNull]" class="flex1 mr10">
                    <el-select v-model="obj.data.shipping_type" placeholder="请选择运输方式">
                        <el-option v-for="(item,index) in obj.config.运输方式||[]" :key="index" :label="item.name" :value="item.name" />
                    </el-select>
                </el-form-item>
                <el-form-item label="产品用途" prop="usage" :rules="[formRulesMixin.notNull]" class="flex1">
                    <el-select v-model="obj.data.usage" placeholder="请选择产品用途" multiple>
                        <el-option v-for="(item,index) in obj.config.产品用途||[]" :key="index" :label="item.name" :value="item.name" />
                    </el-select>
                </el-form-item>
            </div>
            <div class="flex-row">
                <el-form-item label="联系人" prop="contacts" :rules="[formRulesMixin.notNull]" class="flex1 mr10">
                    <el-input v-model="obj.data.contacts" placeholder="请输入联系人" maxlength="20" clearable autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="联系电话" prop="mobile" :rules="[formRulesMixin.notNull]" class="flex1">
                    <el-input v-model="obj.data.mobile" type="number" placeholder="请输入联系电话" maxlength="11" clearable autocomplete="off"></el-input>
                </el-form-item>
            </div>
            <el-form-item label="通讯地址" prop="address" :rules="[formRulesMixin.notNull]" class="flex1">
                <div class="w100 flex-row-center">
                    <el-input v-model="obj.data.address" placeholder="请输入通讯地址" maxlength="100" clearable autocomplete="off" class="flex1 mr5"></el-input>
                    <baiduMap :address="obj.addressInfo" @confirmMapAddress="confirmMapAddress" />
                </div>
            </el-form-item>
            <div class="flex-row">
                <el-form-item label="微信" prop="weixin" class="flex1 mr10">
                    <el-input v-model="obj.data.weixin" placeholder="请输入微信" maxlength="30" clearable autocomplete="off"></el-input>
                </el-form-item>
                <!-- <el-form-item label="QQ" prop="qq" class="flex1">
                    <el-input v-model="obj.data.qq" placeholder="请输入QQ" maxlength="15" clearable autocomplete="off"></el-input>
                </el-form-item> -->
                <el-form-item label="电子邮箱" prop="email" class="flex1 mr10">
                    <el-input v-model="obj.data.email" placeholder="请输入电子邮箱" maxlength="50" clearable autocomplete="off"></el-input>
                </el-form-item>
            </div>
            <!-- <div class="flex-row">
            </div> -->

            <div class="label mt20">优惠方案</div>
            <div class="flex-row mb10">
                <div class="labeltitle flex1">优惠单价（元）</div>
                <div class="labeltitle flex1">计量单位</div>
                <div class="labeltitle flex1">最低起订数</div>
                <el-button :icon="Plus" type="success" size="small" circle @click="addItems({special_price:'',unit:'',min_nums:''},'preferential')" />
            </div>
            <div v-for="(item, i) in obj.data.preferential" :key="i" class="flex-row">
                <el-form-item label="" :prop="`preferential.${i}.special_price`" label-width="0px" class="flex1 mr10">
                    <el-input v-model="obj.data.preferential[i].special_price" type="number" placeholder="请输入优惠单价" maxlength="10" clearable autocomplete="off"><template #append>元</template></el-input>
                </el-form-item>
                <el-form-item label="" :prop="`preferential.${i}.unit`" label-width="0px" class="flex1 mr10">
                    <el-select v-model="obj.data.preferential[i].unit" placeholder="请选择计量单位">
                        <el-option v-for="(item,index) in obj.config.计量单位||[]" :key="index" :label="item.name" :value="item.name" />
                    </el-select>
                </el-form-item>
                <el-form-item label="" :prop="`preferential.${i}.min_nums`" label-width="0px" class="flex1 mr10">
                    <el-input v-model="obj.data.preferential[i].min_nums" type="number" placeholder="请输入最低起订数" maxlength="10" clearable autocomplete="off"></el-input>
                </el-form-item>
                <div style="width: 24px;"><el-button :icon="Delete" type="danger" size="small" circle style="margin-top: 3px;" @click="delItems(i,'preferential')" /></div>
            </div>

            <div class="label require mt20">产品参数</div>
            <div class="flex-row mb10">
                <div class="labeltitle flex1">参数名称</div>
                <div class="labeltitle flex2">参数说明</div>
                <el-button :icon="Plus" type="success" size="small" circle @click="addItems({name:'',desc:''},'parameters')" />
            </div>
            <div v-for="(item, i) in obj.data.parameters" :key="i" class="flex-row">
                <el-form-item label="" :prop="`parameters.${i}.name`" :rules="[formRulesMixin.notNull]" label-width="0px" class="flex1 mr10">
                    <el-select v-model="obj.data.parameters[i].name" placeholder="请选择参数名称">
                        <el-option v-for="(item,index) in obj.config.产品参数||[]" :key="index" :label="item.name" :value="item.name" />
                    </el-select>
                </el-form-item>
                <el-form-item label="" :prop="`parameters.${i}.desc`" :rules="[formRulesMixin.notNull]" label-width="0px" class="flex2 mr10">
                    <el-input v-model="obj.data.parameters[i].desc" placeholder="请输入参数说明" maxlength="100" clearable autocomplete="off"></el-input>
                </el-form-item>
                <div style="width: 24px;"><el-button v-show="obj.data.parameters.length>1" :icon="Delete" type="danger" size="small" circle style="margin-top: 3px;" @click="delItems(i,'parameters')" /></div>
            </div>

            <div class="label require mt20">产品详图</div>
            <div class="flex-row">
                <div class="flex1 mr10 hidden">
                    <el-tooltip effect="dark" content="单选(支持jpeg/jpg/png格式图片,大小不超过5M)" placement="top-start">
                        <div class="desc flex-row-cetner flex1 mb10 lineOne pointer"><el-icon><InfoFilled /></el-icon>单选(支持jpeg/jpg/png格式图片,大小不超过5M)</div>
                    </el-tooltip>
                    <div class="upfilebox flex-row al-flex-start w100 hidden">
                        <el-form-item label="" prop="imgs.cover" label-width="0px">
                            <UpfileSingle type="button" buttontext="上传产品封面图" v-model:file="obj.data.imgs.cover" dir="product" :rules="[formRulesMixin.notNull]" :maxsize="1024*1024*5" :accept="['image/jpeg','image/jpg','image/png']" />
                        </el-form-item>
                    </div>
                </div>
                <div class="flex1 mr10 hidden">
                    <el-tooltip effect="dark" content="多选(支持jpeg/jpg/png格式图片,单张大小不超过5M)" placement="top-start">
                        <div class="desc flex-row-cetner flex1 mb10 lineOne pointer"><el-icon><InfoFilled /></el-icon>多选(支持jpeg/jpg/png格式图片,单张大小不超过5M)</div>
                    </el-tooltip>
                    <div class="upfilebox flex-row al-flex-start w100 mr10 hidden">
                        <el-form-item label="" prop="imgs.albums" label-width="0px">
                            <UpfileMultiple showtype="" buttontext="上传产品相册" v-model:files="obj.data.imgs.albums" dir="product" :maxsize="1024*1024*5" :accept="['image/jpeg','image/jpg','image/png']" />
                        </el-form-item>
                    </div>
                </div>
                <div class="flex1 mr10 hidden">
                    <el-tooltip effect="dark" content="多选(支持mp4格式图片,单个视频大小不超过100M)" placement="top-start">
                        <div class="desc flex-row-cetner flex1 mb10 lineOne pointer"><el-icon><InfoFilled /></el-icon>多选(支持mp4格式图片,单个视频大小不超过100M)</div>
                    </el-tooltip>
                    <div class="upfilebox flex-row al-flex-start w100 mr10 hidden">
                        <el-form-item label="" prop="imgs.videos" label-width="0px">
                            <UpfileMultiple showtype="" buttontext="上传产品视频" v-model:files="obj.data.imgs.videos" dir="product" :maxsize="1024*1024*100" :accept="['video/mp4']" />
                        </el-form-item>
                    </div>
                </div>
            </div>

            <div class="label require mt20">产品详情</div>
            <el-form-item label="" prop="detail" label-width="0px">
                <Editer v-model:value="obj.data.detail" />
            </el-form-item>
        </el-form>
        <div class="btns">
            <el-button @click="$emit('close')">取消</el-button>
            <el-button type="primary" plain @click="preview">预览</el-button>
            <el-button type="primary" @click="upData">提交</el-button>
        </div>

        <el-dialog v-model="obj.dialog.show" :title="obj.dialog.title" width="600px" :close-on-click-modal="false" destroy-on-close>
            <ProductPre :data="obj.dialog.data" @close="obj.dialog.show = false" />
        </el-dialog>
    </div>
</template>

<script setup>
    import { reactive, getCurrentInstance, computed, onMounted } from 'vue'
    import { Plus, Delete, InfoFilled } from '@element-plus/icons-vue'
    import baiduMap from '@/components/baiduMap.vue'
    import Editer from "@/components/editer.vue"
    import UpfileSingle from '@/components/upfile_single.vue'
    import UpfileMultiple from '@/components/upfile_multiple.vue'
    import ProductPre from './productPre.vue'
    let { proxy } = getCurrentInstance()
    const emit = defineEmits(['init', 'close']) //此处要完全对应，采用固定的update:prop属性
    const props = defineProps({
        id: { type: Number, require: true, default: 0 },
    })

    let obj = reactive({
        data:{
            "product_id": props.id,
            "title": "",
            "itemnumber": "",
            "unit": "",
            "min_price": "",
            "shipping_type": "",
            "usage": [],
            "manufactor": "",
            "contacts": "",
            "mobile": "",
            "address": "",
            "location": "",
            "weixin": "",
            "qq": "",
            "email": "",
            "brand": "",
            "preferential": [{special_price:'',unit:'',min_nums:''}],
            "parameters": [{name:'',desc:''}],
            "imgs": {cover: '',albums: '',videos: ''},
            "detail": ""
        },
        localimgs: [],
        addressInfo: {},
        config: {},
        dialog: {
            show: false,
            title: ''
        }
    })

    onMounted(async()=>{
        obj.config = await proxy.$setting.getConfig()
        init()
    })

    let init = async () => {
        if(obj.data.product_id > 0) {
            let o = await get()
            let imgs = {}
            if(!o.imgs||Object.keys(o.imgs).length==0){
                imgs = {cover: '',albums: '',videos: ''}
            }else{
                console.log('o.imgs',o.imgs);
                
                for (const key in o.imgs) {
                    o.imgs[key] = o.imgs[key].split(',')
                    o.imgs[key].map(e=>{
                        let url = e.split(`${proxy.$setting.globalUrl.fileurl}/product/`)[1]
                        if(imgs[key]){
                            imgs[key].push(url)
                        }else{
                            imgs[key] = [url]
                        }
                    })
                    obj.localimgs = obj.localimgs.concat(imgs[key]||[])
                    imgs[key] = imgs[key].join(',')
                }  
            }
            console.log('00',JSON.parse(localStorage.getItem('defaultProdObj')));
            
            obj.data = {
                ...obj.data,
                ...o,
                usage: o.usage?o.usage.split(','):[],
                preferential: (!o.preferential||Object.keys(o.preferential).length==0)?[{special_price:'',unit:'',min_nums:''}]:o.preferential,
                parameters: (!o.parameters||Object.keys(o.parameters).length==0)?[{name:'',desc:''}]:o.parameters,
                imgs: imgs,
            }
            obj.addressInfo = {
                address: o.address,
                longitude: o.location?(o.location.split(',')[0]||''):'',
                latitude: o.location?(o.location.split(',')[1]||''):'',
            } 
        }else{
            const def = localStorage.getItem('defaultProdObj')?JSON.parse(localStorage.getItem('defaultProdObj')):{}//缓存的默认信息
            obj.data = {
                ...obj.data,
                ...def
            }
            obj.addressInfo = {
                address: def.address||'',
                longitude: def.location?(def.location.split(',')[0]||''):'',
                latitude: def.location?(def.location.split(',')[1]||''):'',
            } 
        }
    }

    let get = () => {
        return new Promise((resolve, reject) => {
            proxy.$ajax({
                url: '/manager/product/get',
                data: { product_id: obj.data.product_id },
                bfLoading: true
            }).then(d => {
                resolve(d.msg)
            }).catch(e => {
                reject(e)
            })
        })
    }

    const confirmMapAddress=(e)=>{
        obj.data.address = e.address||obj.data.address
        obj.data.location = `${e.longitude},${e.latitude}`
    }

    const delItems=(i,key)=>{
        if((obj.data[key]&&obj.data[key].length>1)||key=='preferential'){
            obj.data[key].splice(i,1)
        }
    }

    const addItems=(o,key)=>{
        obj.data[key].push(o)
    }

    const preview=()=>{
        const data = getFormdata(false)
        console.log('data',data);
        obj.dialog = {
            show: true,
            title: data.title,
            data: {
                ...data,
                addressInfo: obj.addressInfo
            }
        }
    }

    let upData = () => {
        proxy.$refs['form'].validate(valid => {
            if (valid) {
                const data = getFormdata(true)
                // console.log('data',data);
                // return
                proxy.$ajax({
                    url: '/manager/product/design',
                    data: data,
                    bfLoading: true
                }).then(d => {
                    // console.log(date)
                    if(d.success){
                        proxy.elMessageMixin(`${obj.data.id > 0 ? '修改' : '添加'}成功`, 'success')
                        proxy.$emit('close')
                        proxy.$emit('init')
                        localStorage.setItem("defaultProdObj",JSON.stringify({
                            contacts: data.contacts,
                            weixin: data.weixin,
                            email: data.email,
                            address: data.address,
                            location: data.location,
                        }))
                    }else{
                        ElMessage({ message: d.err, type: 'error', duration: 2 * 1000 })
                    }
                }).catch(() => {})
            } else {
                return false
            }
        })
    }

    const getFormdata=(isUpload)=>{
        let imgs = JSON.parse(JSON.stringify(obj.data.imgs))
        let imgs_ = {}
        for (const key in imgs) {
            imgs[key] = imgs[key].split(',')
            imgs[key].map(e=>{
                let url = `${obj.localimgs.includes(e)?(proxy.$setting.globalUrl.fileurl+'/product'):proxy.$setting.globalUrl.upload}/${e}`
                if(imgs_[key]){
                    imgs_[key].push(url)
                }else{
                    imgs_[key] = [url]
                }
            })
            imgs_[key] = imgs_[key].join(',')
        }
        const data = {
            ...obj.data,
            usage: obj.data.usage.join(','),
            preferential: isUpload?JSON.stringify(obj.data.preferential):obj.data.preferential,
            parameters: isUpload?JSON.stringify(obj.data.parameters):obj.data.parameters,
            imgs: isUpload?JSON.stringify(imgs_):imgs_,
        }
        return data
    }
</script>

<style lang="scss" scoped>
    .label{font-size: 18px;font-weight: bold;margin-bottom: 10px;}
    .labeltitle{font-size: 14px;margin-right: 10px;}
    .require::before{content: '*';color: red;margin-right: 5px;}
    .upfilebox{
        padding: 10px;box-sizing: border-box;
        border: solid 1px #f0f0f0;background: #f9f9f9;
        .desc{font-size: 12px;color: #999;}
    }
    .el-form-item{align-items: flex-start;}
</style>

